﻿using System;
using System.Data;
using System.Configuration;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using SqlScriptRunner.Util;
using DevExpress.XtraEditors;
//using AVPSchemaGenerator.Common;

namespace SqlScriptRunner
{
    public partial class frmServerConfig : XtraForm
    {
        private bool bCmbDatabaseInitialized;
        private bool bCmbServerPopulated;
        private static DataTable dtServers;
        private const string providerName = "SQLServer";

        public string ConnectionString { get; set; }

        public string Database
        {
            get
            {
                if (cmbDatabase.SelectedValue == null)
                {
                    return cmbDatabase.Text;
                }
                return cmbDatabase.SelectedValue.ToString();
            }
        }

        public string Server
        {
            get
            {
                if (cmbServer.SelectedValue == null)
                {
                    return cmbServer.Text;
                }
                return cmbServer.SelectedValue.ToString();
            }
        }

        public frmServerConfig()
        {
            InitializeComponent();
        }

        private string BuildConnectionString()
        {
            return BuildConnectionString(Database);
        }

        private string BuildConnectionString(string sDatabase)
        {
            string str = String.Format("Data Source={0};Initial Catalog={1}", Server, sDatabase);
            if (rbIntegrated.Checked)
            {
                return (String.Format("{0};Integrated Security=SSPI; Connection Timeout=0", str));
            }
            string str2 = str;
            return (String.Format("{0};User ID={1};Password={2}; Connection Timeout=0", str2, tbUsername.Text, tbPassword.Text));
        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            string connectionString = BuildConnectionString();
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    connection.Close();
                    MessageBox.Show("Test connection succeed.", "Test Connection");
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(String.Format("Test Connection failed.\n\nError:\n{0}", exception.Message), "Test Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            using (frmSaveConnection connection = new frmSaveConnection())
            {
                if (connection.ShowDialog() == DialogResult.OK)
                {
                    string connectionName = connection.ConnectionName;
                    string connectionString = BuildConnectionString();
                    Configuration configuration = ConfigurationManager.OpenExeConfiguration(Path.Combine(Environment.CurrentDirectory, "SqlScriptRunner.exe"));
                    ConnectionStringSettings settings = new ConnectionStringSettings(String.Format("SQLServer_{0}", connectionName), connectionString, "SQLServer");
                    configuration.ConnectionStrings.ConnectionStrings.Add(settings);
                    configuration.Save(ConfigurationSaveMode.Modified);
                    LoadSavedConnections();
                }
            }
        }

        private void LoadSavedConnections()
        {
            treeStoredConnections.BeginUpdate();
            treeStoredConnections.Nodes.Clear();
            TreeNode node = new TreeNode("SQL Server Connections", 1, 1);
            string executablePath = Application.ExecutablePath;
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(executablePath);
            ConfigurationManager.RefreshSection(String.Format("{0}.config", executablePath));
            foreach (ConnectionStringSettings settings in configuration.ConnectionStrings.ConnectionStrings)
            {
                if (settings.ProviderName == "SQLServer")
                {
                    TreeNode node2 = new TreeNode(settings.Name.Replace("SQLServer_", ""), 0, 0);
                    node2.ToolTipText = settings.ConnectionString;
                    node2.Tag = settings;
                    node.Nodes.Add(node2);
                }
            }
            treeStoredConnections.Nodes.Add(node);
            treeStoredConnections.ExpandAll();
            treeStoredConnections.EndUpdate();
        }

        private void PopulateFieldsFromConnectionString(string connectionString)
        {
            string[] strArray = connectionString.Split(";".ToCharArray());
            for (int i = 0; i < strArray.Length; i++)
            {
                string[] strArray2 = strArray[i].Split("=".ToCharArray());
                string str = strArray2[0];
                if (str != null)
                {
                    if (str.Equals("data source", StringComparison.OrdinalIgnoreCase))
                    {
                        cmbServer.SelectedItem = null;
                        cmbServer.Text = strArray2[1];
                    }
                    else if (str.Equals("initial catalog", StringComparison.OrdinalIgnoreCase))
                    {
                        cmbDatabase.SelectedItem = null;
                        cmbDatabase.Text = strArray2[1];
                    }
                    else if (str.Equals("integrated security", StringComparison.OrdinalIgnoreCase))
                    {
                        rbIntegrated.Checked = true;
                        rbSQL.Checked = false;
                    }
                    else if (str.Equals("user id", StringComparison.OrdinalIgnoreCase))
                    {
                        rbIntegrated.Checked = false;
                        rbSQL.Checked = true;
                        tbUsername.Text = strArray2[1];
                    }
                    else if (str.Equals("password", StringComparison.OrdinalIgnoreCase))
                    {
                        tbPassword.Text = strArray2[1];
                    }
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            ConnectionString = BuildConnectionString();
        }

        private void rbIntegrated_CheckedChanged(object sender, EventArgs e)
        {
            bCmbDatabaseInitialized = false;
            CheckRadioBtnState();
        }

        private void CheckRadioBtnState()
        {
            if (rbIntegrated.Checked)
            {
                tbPassword.Enabled = false;
                tbUsername.Enabled = false;
            }
            else
            {
                tbPassword.Enabled = true;
                tbUsername.Enabled = true;
            }
        }

        private void ClearConnectionFields()
        {
            tbPassword.Text = string.Empty;
            tbUsername.Text = string.Empty;
            rbIntegrated.Checked = true;
            rbSQL.Checked = false;
            cmbDatabase.SelectedIndex = -1;
            cmbDatabase.SelectedText = string.Empty;
            cmbDatabase.SelectedValue = string.Empty;
            cmbServer.SelectedIndex = -1;
            cmbServer.SelectedText = string.Empty;
            cmbServer.SelectedValue = string.Empty;
        }

        private void cmbServer_DropDown(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                if (!bCmbServerPopulated)
                {
                    if (Constant.SQLServerInstances == null) Constant.FindMSSQLInstances();
                    cmbServer.ValueMember = "ServerName";
                    cmbServer.DisplayMember = "ServerName";
                    cmbServer.DataSource = Constant.SQLServerInstances;
                    cmbServer.SelectedIndex = -1;
                    bCmbServerPopulated = true;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Could not establish connection to the server.");
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void cmbDatabase_DropDown(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                string selectCommandText = " select [name] from master..sysdatabases order by [name]";
                using (SqlConnection connection = new SqlConnection(BuildConnectionString("master")))
                {
                    connection.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(selectCommandText, connection);
                    using (DataSet dataSet = new DataSet())
                    {
                        adapter.Fill(dataSet);
                        cmbDatabase.ValueMember = "name";
                        cmbDatabase.DisplayMember = "name";
                        cmbDatabase.DataSource = dataSet.Tables[0];
                    }
                    if (connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                    }
                    adapter.Dispose();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void treeStoredConnections_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Parent == null)
            {
                ClearConnectionFields();
            }
            else
            {
                ConnectionStringSettings tag = e.Node.Tag as ConnectionStringSettings;
                if (tag == null)
                {
                    ClearConnectionFields();
                }
                else
                {
                    PopulateFieldsFromConnectionString(tag.ConnectionString);
                }
            }
        }

        private void frmServerConfig_Load(object sender, EventArgs e)
        {
            CheckRadioBtnState();
            try
            {
                LoadSavedConnections();
            }
            catch
            {
                MessageBox.Show("Could not load configuration file. Be sure that AVPGUI.exe.config exists on your system.");
            }
        }

        private void contextMenuItemDelete_Click(object sender, EventArgs e)
        {
            if (treeStoredConnections.SelectedNode == null)
            {
                MessageBox.Show("Please select one of the connection nodes bellow to be deleted.", "Remove Connection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (treeStoredConnections.SelectedNode.Parent == null)
            {
                MessageBox.Show("Please select one of the connection nodes bellow to be deleted.", "Remove Connection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                string text = treeStoredConnections.SelectedNode.Text;
                ConnectionStringSettings tag = treeStoredConnections.SelectedNode.Tag as ConnectionStringSettings;
                if (tag == null)
                {
                    MessageBox.Show("Some problem appears trying to remove selected connection. Selection will not be removed.", "Remove Connection", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
                else if (MessageBox.Show("Are you sure you want to delete selected connection from the list?", "Remove Connection", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    string exePath = Path.Combine(Environment.CurrentDirectory, "AVPGUI.exe");
                    System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(exePath);
                    ConfigurationManager.RefreshSection(String.Format("{0}.config", exePath));
                    ConnectionStringSettingsCollection connectionStrings = configuration.ConnectionStrings.ConnectionStrings;
                    configuration.ConnectionStrings.ConnectionStrings.Remove(tag);
                    configuration.Save(ConfigurationSaveMode.Modified);
                    LoadSavedConnections();
                }
            }
        }
    }
}
